package com.woniuxy.charin.service.impl;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.charin.mapper.ChargingRecordsMapper;
import com.woniuxy.charin.mapper.TransactionOrderMapper;
import com.woniuxy.charin.model.dto.ChargingData;
import com.woniuxy.charin.model.entity.ChargingRecords;
import com.woniuxy.charin.model.entity.TransactionOrder;
import com.woniuxy.charin.model.vo.ChargingRecordsVo;
import com.woniuxy.charin.provider.ChargingDataProvider;
import com.woniuxy.charin.service.ChargingRecordsService;
import com.woniuxy.charin.service.TransactionOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【charging_records(充电记录表)】的数据库操作Service实现
* @createDate 2024-12-24 10:20:38
*/
@Service
public class ChargingRecordsServiceImpl extends ServiceImpl<ChargingRecordsMapper, ChargingRecords> implements ChargingRecordsService {

    @Override
    public boolean addChargingRecord(ChargingRecords chargingRecord) {
        // 设置创建时间为当前时间
        chargingRecord.setCreateTime(new Date());

        // 调用 MyBatis-Plus 提供的保存方法
        return this.save(chargingRecord);
    }


    @Autowired
    private ChargingRecordsMapper chargingRecordsMapper;

    @Autowired
    private ChargingDataProvider chargingDataProvider;

    @Autowired
    private TransactionOrderMapper transactionOrderMapper;

    public ChargingRecords createChargingRecord(String orderNumber) {
        // 从硬件或服务接口获取实时充电数据
        ChargingData data = chargingDataProvider.getChargingData(orderNumber);

        // 创建充电记录对象并填充数据
        ChargingRecords record = new ChargingRecords();
        record.setOrderNumber(orderNumber);
        record.setCreateTime(new Date());
//        record.setCustomerName(data.getCustomerName());
//        record.setPhoneNumber(data.getPhoneNumber());
//        record.setChargingPower(data.getChargingPower());
//        record.setPaymentMethod(data.getPaymentMethod());
//        record.setChargingCost(data.getChargingCost());
//        record.setChargingStationName(data.getChargingStationName());



//        record.setChargingPileNumber(data.getChargingPileNumber());
//        record.setOperationStatus("已完成");

        // 使用 MyBatis-Plus 提供的 insert 方法插入记录
        chargingRecordsMapper.insert(record);

        return record;
    }

    @Override
    public Page<ChargingRecordsVo> getChargingRecords(Map<String, Object> queryParams, int pageNum, int pageSize) {
        Page<ChargingRecordsVo> page = new Page<>(pageNum, pageSize);
        return chargingRecordsMapper.selectChargingRecords(page, queryParams);
    }




/**
 * 提交退款申请
 */
@Override
public boolean submitRefund(String orderNumber, String refundDescription, Double refundAmount) {
    // 查询对应的充电记录
    ChargingRecords record = chargingRecordsMapper.findByOrderNumber(orderNumber);
    if (record == null) {
        throw new RuntimeException("未找到对应的充电记录");
    }

    // 检查退款金额是否合理（使用 BigDecimal.compareTo）
    BigDecimal refundAmountDecimal = BigDecimal.valueOf(refundAmount);
    if (refundAmountDecimal.compareTo(record.getAmount()) > 0) {
        throw new RuntimeException("退款金额不能超过消费金额");
    }

    // 更新退款相关信息
    record.setRefundDescription(refundDescription);
    record.setRefundAmount(refundAmountDecimal);
    record.setRefundStatus(1); // 1表示退款处理中
    record.setRefundTime(new Date()); // 设置当前时间为退款时间

    // 保存更新后的记录
    int rowsUpdated = chargingRecordsMapper.updateRefundInfo(record);
    return rowsUpdated > 0;
}



    @Override
    public ChargingRecordsVo getChargingRecordById(Long id) {
        ChargingRecordsVo recordVo = chargingRecordsMapper.findChargingRecordVoById(id);
        if (recordVo == null) {
            throw new RuntimeException("充电记录未找到，ID：" + id);
        }
        // 直接返回原始或轻度加工后的数据
        return recordVo;
    }

    /**
     * 处理退款申请
     *
     * @param orderNumber        充电订单号
     * @param processDescription 退款处理说明
     * @return 是否处理成功
     */
    @Override
    public boolean processRefund(String orderNumber, String processDescription) {
        // 查询充电记录
        ChargingRecords record = chargingRecordsMapper.findByOrderNumber(orderNumber);
        if (record == null) {
            throw new RuntimeException("未找到对应的充电记录");
        }

        // 检查退款状态，确保只有“处理中”状态可以被处理
        if (record.getRefundStatus() != 1) {
            throw new RuntimeException("退款状态不允许处理");
        }

        // 更新退款相关信息
        record.setProcessDescription(processDescription);
        record.setRefundStatus(2); // 2 表示已完成退款

        // 更新记录到数据库
        int rowsUpdated = chargingRecordsMapper.updateRefundInfo1(record);
        return rowsUpdated > 0;
    }

    // 生成充电订单号
    public String generateOrderNumber() {
        return "CD" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }

    @Transactional
    public void handleCharging(Long customerId, Long pileId, BigDecimal amount, Long paymentId) {
        // 生成充电订单号
        String orderNumber = generateOrderNumber();

        // 插入充电记录
        ChargingRecords chargingRecord = new ChargingRecords();
        chargingRecord.setOrderNumber(orderNumber);
        chargingRecord.setCustomerId(customerId);
        chargingRecord.setPileId(pileId);
        chargingRecord.setAmount(amount);
        chargingRecord.setPaymentId(paymentId);
        chargingRecord.setStatus("已完成");
        chargingRecord.setCreateTime(new Date());
        chargingRecordsMapper.insert(chargingRecord);

        // 插入交易流水
        TransactionOrder transactionOrder = new TransactionOrder();
        transactionOrder.setOrderNo(orderNumber);
        transactionOrder.setCustomerId(Math.toIntExact(customerId));
        transactionOrder.setTransactionType("充电");
        transactionOrder.setTransactionAmount(amount);
        transactionOrder.setPaymentMethodId(paymentId);
        transactionOrder.setStatus(1); // 已完成
        transactionOrder.setCreateTime(new Date());
        transactionOrderMapper.insert(transactionOrder);
    }

    @Transactional
    public void handleRefund(String originalOrderNo, BigDecimal refundAmount, String refundReason) {
        // 查找原订单
        ChargingRecords record = chargingRecordsMapper.findByOrderNumber(originalOrderNo);
        if (record == null) {
            throw new RuntimeException("未找到对应的充电记录");
        }

        // 更新充电记录的退款信息
        record.setRefundAmount(refundAmount);
        record.setRefundDescription(refundReason);
        record.setRefundStatus(2); // 已退款
        record.setRefundTime(new Date());
        chargingRecordsMapper.updateRefundInfo(record);

        // 插入交易流水
        TransactionOrder transactionOrder = new TransactionOrder();
        transactionOrder.setOrderNo(originalOrderNo);
        transactionOrder.setCustomerId(Math.toIntExact(record.getCustomerId()));
        transactionOrder.setTransactionType("退款");
        transactionOrder.setTransactionAmount(refundAmount.negate()); // 负值表示退款
        transactionOrder.setStatus(1); // 已完成
        transactionOrder.setCreateTime(new Date());
        transactionOrderMapper.insert(transactionOrder);
    }




}


